/**
 * Created by wxb on 2016/10/12.
 */
(function () {
  'use strict';

  angular.module('BlurAdmin.theme.components')
    .controller('ImageUploadNewCtrl', ImageUploadNewCtrl);

  /** @ngInject */
  function ImageUploadNewCtrl($scope, $q, $qupload, $log, qiniuToken, rfc4122, $uibModal, SweetAlert) {
    var token;
    var imgBaseUrl;

    if ($scope.imgObject.ARmagicLibrary) {
      qiniuToken.cooperationToken().then(function (data) {
        token = data.data.token;
      });
      qiniuToken.productBaseUrl().then(function (data) {
        imgBaseUrl = data;
      });
    }
    else {
      qiniuToken.imgToken().then(function (data) {
        token = data.data.token;
      });
      qiniuToken.imgBaseUrl().then(function (data) {
        imgBaseUrl = data;
      });
    }

    $scope.imgSelectFiles = [];
    $scope.imgUploading = false;

    var start = function (index) {
      console.log($scope.imgSelectFiles[index].file.name)
      $scope.imgSelectFiles[index].progress = {
        p: 0
      };
      $scope.imgSelectFiles[index].upload = $qupload.upload({
        key: ($scope.imgObject.key) + rfc4122.v4() + '.' + $scope.imgSelectFiles[index].file.name.split(".").pop(),
        file: $scope.imgSelectFiles[index].file,
        token: token
      });
      $scope.imgSelectFiles[index].upload.then(function (response) {
        $log.info(response);
        if (!$scope.imgObject.multiple) {
          $scope.imgObject.imgUrl = imgBaseUrl + response.key;
          $scope.imgObject.uploadImgUrl = response.key;
          if ($scope.imgObject.needSize) {
            var f = $scope.imgSelectFiles[index].file;
            var reader = new FileReader();
            reader.onload = function (e) {
              var data = e.target.result;
              var image = new Image();
              image.onload = function(){
                $scope.imgObject.imgWidth = image.width;
                $scope.imgObject.imgHeight = image.height;
                $scope.$apply();
                console.log($scope.imgObject);
              };
              image.src= data;
            };
            reader.readAsDataURL(f);
          }
        }
        else {
          $scope.imgObject.imgUrl.push({
            url: imgBaseUrl + response.key,
            name: $scope.imgSelectFiles[index].file.name.split(".")[0],
          });
        }
        $scope.imgUploading = false;
      }, function (response) {
        $log.info(response);
      }, function (evt) {
        $scope.imgSelectFiles[index].progress.p = Math.floor(100 * evt.loaded / evt.totalSize);
        $scope.imgProgressbarValue = $scope.imgSelectFiles[index].progress.p;
        if (evt) {
          $scope.imgUploading = true;
        }
      });
    };

    $scope.abort = function (index) {
      $scope.imgSelectFiles[index].upload.abort();
      $scope.imgSelectFiles.splice(index, 1);
      $scope.imgUploading = false;
    };

    $scope.onImgSelect = function ($files) {
      if ($scope.imgObject.needCrop) {
        var cropSrcFile = $files.slice(-1)[0];
        var cropSrcFileName = cropSrcFile.name;
        getBase64(cropSrcFile).then(function (base64Data) {
          var modalInstance = $uibModal.open({
            backdrop  : 'static',
            keyboard  : false,
            animation: true,
            templateUrl: 'app/theme/components/imageUpload/modal/imageCrop.html',
            controller: 'ImageCropModalCtrl',
            resolve: {
              cropSrc: function () {
                return base64Data;
              },
              cropWidth: function () {
                return $scope.imgObject.cropWidth;
              },
              cropHeight: function () {
                return $scope.imgObject.cropHeight;
              }
            }
          });
          modalInstance.result.then(function (modalItem) {
            var cropFile = dataURLtoFile(modalItem, cropSrcFileName);
            var files = [];
            files.push(cropFile);
            var offsetx = $scope.imgSelectFiles.length;
            for (var i = 0; i < files.length; i++) {
              $scope.imgSelectFiles[i + offsetx] = {
                file: files[i]
              };
              start(i + offsetx);
            }
          })
        });
      }
      else {
        if ($files.length <= 100) {
          var offsetx = $scope.imgSelectFiles.length;
          for (var i = 0; i < $files.length; i++) {
            $scope.imgSelectFiles[i + offsetx] = {
              file: $files[i]
            };
            start(i + offsetx);
          }
        }
        else {
          toastr.error('一次上传的图片不能超过100张', '失败!');
        }
      }
    };


    function getBase64(file) {
      var deferred = $q.defer();
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function () {
        deferred.resolve(reader.result);
      };
      reader.onerror = function (error) {
        console.log('Error: ', error);
        deferred.resolve(undefined);
      };
      return deferred.promise;
    }

    function dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while(n--){
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type:mime});
    }

    // //for paste img
    // if (!window.Clipboard) {
    //   var pasteCatcher = document.createElement("div");
    //   pasteCatcher.setAttribute("contenteditable", "");
    //   pasteCatcher.style.opacity = 0;
    //   document.body.appendChild(pasteCatcher);
    // }
    // window.addEventListener("paste", pasteHandler);
    //
    // function pasteHandler(e) {
    //   console.log(e)
    //   if (e.clipboardData) {
    //     var items = e.clipboardData.items;
    //     if (items) {
    //       for (var i = 0; i < items.length; i++) {
    //         if (items[i].type.indexOf("image") !== -1) {
    //           // get the blob
    //           var imageFile = items[i].getAsFile();
    //           //console.log(imageFile);
    //           var reader = new FileReader();
    //           reader.onload = function(event) {
    //             //console.log(event.target.result); // data url!
    //             var imgName = 'paste' + Math.floor(Math.random() * ( 100000 + 1)) + '.png';
    //             //console.log(imgName);
    //             submitFileForm(event.target.result, imgName);
    //           };
    //           reader.readAsDataURL(imageFile);
    //         }
    //       }
    //     }
    //   }
    // }
    //
    // function submitFileForm(dataUrl, filename) {
    //   var cropFile = dataURLtoFile(dataUrl, filename);
    //   var files = [];
    //   files.push(cropFile);
    //   var offsetx = $scope.imgSelectFiles.length;
    //   for (var i = 0; i < files.length; i++) {
    //     $scope.imgSelectFiles[i + offsetx] = {
    //       file: files[i]
    //     };
    //     start(i + offsetx);
    //   }
    // }

    $scope.deleteImg = function (it, index) {
      SweetAlert.swal({
            title: "确定删除?",
            text: "您将要删除此会议PPT!",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            closeOnConfirm: true},
          function(isConfirm) {
            if (isConfirm) {
              $scope.$emit('delete_img_event', it);
              $scope.imgObject.imgUrl.splice(index, 1);
            }
          });
    }

  }
})();

